﻿// ==================================================================================================
// Copyright(C) 2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME	    : FI.Net Application Framework
// COMPONENT ID	    : FI.Core
// COMPONENT DESC   : The foundation component of the whole framework. 	
//
// CREATED DATE/BY  : 30 Nov 2011 / Tian Mi
//
// REVISION HISTORY :	
// DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
using Microsoft.Practices.Unity.ObjectBuilder;
using Microsoft.Practices.Unity.Utility;

namespace FI.Core.IoC
{
    /// <summary>
    /// A <see cref="UnityContainerExtension"/> for automatic interception.
    /// </summary>
    public class AutoInterception : UnityContainerExtension
    {
        /// <summary>
        /// Registers the default interceptor.
        /// </summary>
        /// <param name="interceptor">The interceptor.</param>
        /// <returns></returns>
        public IUnityContainer RegisterDefaultInterceptor(IInstanceInterceptor interceptor)
        {
            Guard.ArgumentNotNull(interceptor, "interceptor");
            FixedAutoInterceptorPolicy fixedAutoInterceptorPolicy = new FixedAutoInterceptorPolicy(interceptor);
            this.Container.RegisterInstance(typeof(AutoInterceptorPolicy), typeof(AutoInterceptorPolicy).AssemblyQualifiedName, fixedAutoInterceptorPolicy, new ContainerControlledLifetimeManager());
            return this.Container;
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        protected override void Initialize()
        {
            base.Context.Strategies.AddNew<AutoInterceptionStrategy>(UnityBuildStage.Setup);
            TransparentProxyInterceptor interceptor = new TransparentProxyInterceptor();
            base.Context.Container.RegisterInstance<IInstanceInterceptor>(typeof(IInstanceInterceptor).AssemblyQualifiedName, interceptor);
            base.Context.Container.RegisterInstance<AutoInterceptorPolicy>(typeof(AutoInterceptorPolicy).AssemblyQualifiedName, new FixedAutoInterceptorPolicy(interceptor));
        }
    }
}
